package com.boarsoft.soagov.javaagent;

import java.lang.reflect.Modifier;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

/**
 * RPC service APM transformer
 * 
 * @author Mac_J
 *
 */
public class ServiceTransformer implements ClassTransformer {
	private static Logger log = LoggerFactory.getLogger(ServiceTransformer.class);

	@Override
	public byte[] transform(ClassPool cp, String cn) throws Exception {
		// TODO 自定义的过滤条件
		if (!cn.startsWith("com/boarsoft/rpc/demo") || !cn.endsWith("ServiceImpl")) {
			return null;
		}
		CtClass cc = cp.getCtClass(cn.replaceAll("/", "."));
		if (cc.isInterface()) {
			return null;
		}
		log.warn("Transform class {}", cn);
		CtMethod[] methods = cc.getDeclaredMethods();
		for (CtMethod m : methods) {
			if (Modifier.isPublic(m.getModifiers())) {
				m.addLocalVariable("_$st", CtClass.longType);
				m.insertBefore("_$st = System.currentTimeMillis();");
				m.insertAfter("log.info(\"_$>Elapsed {}ms\", new Long(System.currentTimeMillis() - _$st));");
			}
		}
		return cc.toBytecode();
	}

}
